<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图区-->
        <el-card>
            <!--搜索与添加区-->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="输入用户名" v-model="queryInfo.request.account" clearable @clear="getList">
<!--                        <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>-->
                        <el-button slot="append" icon="el-icon-search" ></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>


            <!--用户列表区-->
            <el-table :data="users" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="用户账号" prop="account"></el-table-column>
                <el-table-column label="用户名称" prop="name"></el-table-column>
                <el-table-column label="角色" prop="roles"></el-table-column>
                <el-table-column label="邮箱" prop="email" width="160px"></el-table-column>
                <el-table-column label="最后登录时间" prop="updateTime" width="160px"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.status">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150px">
                    <template>
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini"
                                   @click="editDialogVisible = true"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                                   @click="removeUserById"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!--分页区-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.page"
                    :page-sizes="[1, 2, 5, 10]"
                    :page-size="queryInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"></el-pagination>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog
                title="添加用户"
                :visible.sync="addDialogVisible"
                width="50%">
            <!--内容主体区-->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="账号名" prop="account">
                    <el-input v-model="addForm.account"></el-input>
                </el-form-item>

                <el-form-item label="用户名" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>

                <el-form-item label="角色" prop="role">
                    <el-select v-model="value" placeholder="请选择">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <!--内容底部区-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改用户对话框 -->
        <el-dialog
                title="修改用户"
                :visible.sync="editDialogVisible"
                width="50%">
            <!--内容主体区-->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="账号名" prop="account">
                    <el-input v-model="editForm.account"  disabled></el-input>
                </el-form-item>

                <el-form-item label="用户名" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="editForm.password"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>

                <el-form-item label="角色" prop="role">
                    <el-select v-model="value" placeholder="请选择">
                        <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <!--内容底部区-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import qs from 'qs'
    export default {
        name: "User",
        data() {
             /*验证邮箱规则*/
            var checkEmail = (rule, value, cb) => {
                // 验证邮箱的正则表达式
                const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

                if (regEmail.test(value)) {
                    return cb()
                }
                cb(new Error('请输入合法邮箱'))
            }

            return {
                /*获取用户列表的参数对象, 分页*/
                queryInfo: {
                    page : 4,
                    pageSize:5,
                    request:{
                        account:"",
                    },
                },
                total: 0,
                /*json相关*/
                users: [],
                /*控制添加用户的显示与隐藏对话框*/
                addDialogVisible: false,
                /*添加用户的表单数据*/
                addForm: {
                    account: 'admin01',
                    name: '测试人员',
                    password: '123456',
                    email: '168852@163.com',
                    roles: ''
                },
                /* 添加表单的验证规则*/
                addFormRules: {
                    account: [
                        {required: true, message: '请输入账号名', trigger: 'blur'},
                        {min: 3, max: 10, message: '账号名的长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    name: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 10, message: '用户名的长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 6, message: '密码的长度在 3 到 6 个字符', trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ]
                },

                /*修改表单的验证规则*/
                editFormRules: {
                    account: [
                        {required: true, message: '请输入账号名', trigger: 'blur'},
                        {min: 3, max: 10, message: '账号名的长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    name: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 10, message: '用户名的长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 6, message: '密码的长度在 3 到 6 个字符', trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ]
                },

                /*多选*/
                options: [{
                    value: '1',
                    label: '系统管理员'
                }, {
                    value: '2',
                    label: '线路管理员'
                }, {
                    value: '3',
                    label: '巡检员'
                }, {
                    value: '4',
                    label: '消缺员'
                }],

                value: '',
                /*查询到的用户信息对象*/
                editForm: {},

                /*控制修改用户对话框的显示隐藏*/
                editDialogVisible: false,
            }
        },
        /*json相关*/
        created() {
            this.getUserList()
        },
        methods: {
            /*查询列表*/
            async getUserList() {
                const {data: res} = await this.$http.post('/system/user/query',this.queryInfo)
                this.users = res.data.result
            },
            /*getList() {
                this.axios.get('/user.json').then((res) => {
                    this.menus = res.data.result
                    this.total = res.data.total
                })
            },*/
            /*监听 pagesize 改变的事件*/
            /*handleSizeChange(newSize) {
                this.queryInfo.pagesize = newSize
                this.getList()
            },*/
            /*监听页码值改变的事件*/
            /*handleCurrentChange(newPage) {
                this.queryInfo.pagenum = newPage
                this.getList()
            },*/

            /*监听 switch 开关状态的改变*/
            /*async userStateChanged(userinfo) {
                console.log(userinfo)
                const {data: res} = await this.$http.put(
                    `system/${userinfo.id}/stop/${userinfo.state}`)
                if (res.meta.status !== 101) {
                    userinfo.state = !userinfo.state
                    return this.$message.error('更新用户状态失败')
                }
                this.$message.success('更新用户状态成功')
            },*/

            /*监听添加用户对话框的关闭事件*/
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()
            },

            /*点击按钮，新增用户*/
            addUser() {
                this.$refs.addFormRef.validate(async valid => {
                    let data = qs.stringify(this.addForm)
                    if (!valid) return
                    // 发起添加网络的请求
                    const {data: res} = await this.$http.post('system/user/add',data)
                    console.log(data)
                    if (res.code !==200) {
                        this.$message.error('添加用户失败')
                    }
                    this.$message.success('添加用户成功')
                    // 隐藏添加用户的对话框
                    this.addDialogVisible = false
                    // 重新获取用户列表数据
                    this.getUserList()
                })
            },

            // 修改用户信息并提交
            /*editUserInfo() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) return
                    // 发起修改用户信息的数据请求
                    const {data: res} = await this.$http.put('system/roles/update/' + this.editForm.id, {
                        email: this.editForm.email
                    })

                    if (res.meta.status !== 101) {
                        this.$message.error('更新用户信息失败')
                    }
                    // 提示修改成功
                    this.$message.success('更新用户信息成功')
                    // 关闭对话框
                    this.editDialogVisible = false
                    // 刷新数据列表
                    this.getList()
                })
            },*/

            //根据Id删除对应用户信息
            async removeUserById(id) {
                // 弹框询问管理员是否删除用户
                const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                // 如果用户确认删除，则返回值为字符串confirm
                // 如果用户取消删除，则返回值为字符串cancel
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已经取消了删除')
                }
                const {data: res} = await this.$http.delete('users/' + id)
                if (res.meta.status !== 101) {
                    return this.$message.error('删除用户失败')
                }
                this.$message.success('删除成功')
                // 刷新列表
                this.getUserList()
            }
        }
    }
</script>

<style scoped lang="less">

</style>
